package com.joy.openggl.util;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.nio.ShortBuffer;

public class BufferUtil {

	public static IntBuffer intBuffer(int[] a) {
		// int is 4 bytes, therefore we multiply  
	    //the number if  
	    // vertices with 4. 
        ByteBuffer mbb = ByteBuffer.allocateDirect(a.length * 4);    
        // 数组排列用nativeOrder 
        mbb.order(ByteOrder.nativeOrder());    
        IntBuffer iBuffer = mbb.asIntBuffer();    
        iBuffer.put(a);    
        iBuffer.position(0);  
        
        return iBuffer;    
    }   
	
	public static FloatBuffer floatBuffer(float[] a) {    
		// float is 4 bytes, therefore we multiply  
	    //the number if  
	    // vertices with 4. 
        ByteBuffer mbb = ByteBuffer.allocateDirect(a.length * 4);
        //数组排列用nativeOrder    
        mbb.order(ByteOrder.nativeOrder());    
        FloatBuffer fBuffer = mbb.asFloatBuffer();    
        fBuffer.put(a);    
        fBuffer.position(0);  
        
        return fBuffer;    
    }
	
	public static ShortBuffer shortBuffer(short[] a) {    
		// short is 2 bytes, therefore we multiply  
	    //the number if  
	    // vertices with 2. 
        ByteBuffer mbb = ByteBuffer.allocateDirect(a.length * 2);
        //数组排列用nativeOrder    
        mbb.order(ByteOrder.nativeOrder());    
        ShortBuffer sBuffer = mbb.asShortBuffer();    
        sBuffer.put(a);    
        sBuffer.position(0);  
        
        return sBuffer;    
    }
	
	public static ByteBuffer byteBuffer(byte[] a) {    
		
		return ByteBuffer.wrap(a);
    }
	
	/**
	 * 顶点坐标
	 */
	public static FloatBuffer getVerticesBuffer(float cx, float cy, float cw, float ch) {
		return floatBuffer(getVertices(cx, cy, cw, ch));
	}
	/**
	 * 顶点坐标
	 */
	public static float[] getVertices(float cx, float cy, float cw, float ch) {
		cw = cx + cw;
		ch = cy + ch;
		float[] vertices = new float[8];
		vertices[0] = (cx);
		vertices[1] = (cy);
		vertices[2] = (cw);
		vertices[3] = (cy);
		vertices[4] = (cx);
		vertices[5] = (ch);
		vertices[6] = (cw);
		vertices[7] = (ch);
		return vertices;
	}

	/**
	 * 纹理坐标
	 */
	public static FloatBuffer getTexcoordsBuffer(float cx, float cy, float cw, float ch, float tw, float th) {
		return floatBuffer(getTexcoords(cx, cy, cw, ch, tw, th));
	}
	/**
	 * 纹理坐标
	 */
	public static float[] getTexcoords(float cx, float cy, float cw, float ch, float tw, float th) {
		float[] texcoords = new float[8];
		texcoords[0] = (cx) / tw;
		texcoords[1] = (cy) / th;
		texcoords[2] = (cx + cw) / tw;
		texcoords[3] = texcoords[1];
		texcoords[4] = texcoords[0];
		texcoords[5] = (cy + ch) / th;
		texcoords[6] = texcoords[2];
		texcoords[7] = texcoords[5];
		return texcoords;
	}
}
